package com.xyh.eduservice.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xyh.commonutils.JwtUtils;
import com.xyh.commonutils.R;
import com.xyh.eduservice.client.UcenterClient;
import com.xyh.eduservice.entity.EduComment;
import com.xyh.eduservice.service.EduCommentService;
import com.xyh.servicebase.exceptionHandler.GuliException;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * <p>
 * 评论 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2022-08-16
 */
@RestController
@RequestMapping("/eduservice/comment")
//@CrossOrigin
public class EduCommentController {

    @Resource
    private UcenterClient ucenterClient;
    @Resource
    private EduCommentService commentService;

    //分页查询
    @GetMapping("/{page}/{limit}")
    public R getPageList(@PathVariable("page")Long page,@PathVariable("limit")Long limit,
                         String courseId){
        Page<EduComment> commentPage = new Page<>(page,limit);
        Map<String,Object> map = commentService.getCommentPageList(commentPage,courseId);
        return R.ok().data(map);
    }

    //添加数据
    @PostMapping("/auth/save")
    public R addComment(@RequestBody EduComment comment,HttpServletRequest request){
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if (StringUtils.isEmpty(memberId)){
            throw new GuliException(20001,"请登录");
        }
        Map<String, Object> map = ucenterClient.getMemberById(memberId);
        Object object = map.get("ucenterInfo");
        String jsonObject = JSON.toJSONString(object);
        EduComment userInfo = JSONObject.parseObject(jsonObject, EduComment.class);
        comment.setId(memberId);
        comment.setNickname(userInfo.getNickname());
        comment.setAvatar(userInfo.getAvatar());
        commentService.save(comment);
        return R.ok();
    }



}

